package com.demo.framework.http;

import java.util.List;

import jitmarketing.android.framework.network.NetworkException;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * 
 * @ClassName: PostHttpDataHelper
 * @Description: TODO(提交数据，包括图片等数据)
 * @author 谢云腾
 * @date 2013-4-3 上午09:57:40
 * @version 1.0
 */
public class PostHttpDataHelper {

    private String baseURL = "";

    private List<RequestParameter> parameter;

    private HttpRequest httpRequest = null;

    public PostHttpDataHelper(String baseUrl) {
        this.baseURL = baseUrl;
        httpRequest = new HttpRequest();
    }

    /**
     * 调用WCF Web Service，POST JSON格式参数，将Response转换为JSON对象
     * 
     * @param method
     *            Web Service 方法名
     * @param paramNamne
     *            Web Service 给定方法 参数名
     * @return JSON对象
     */
    public JSONObject postJSON(String method, String paramNamne, JSONObject paramObj) throws JSONException {
        String resp = postJSONAndGetString(method, paramNamne, paramObj);
        return resp == null ? null : new JSONObject(resp);
    }

    /**
     * 调用WCF Web Service，POST JSON格式参数，将Response转换为byte array
     * 
     * @param method
     * @param param
     * @return
     */
    public byte[] postJSON(String method, JSONObject param) {
        byte[] resp = null;
        httpRequest.setRequestProperty("Accept", "application/json");
        httpRequest.setRequestProperty("Content-type", "application/json");
        String url = baseURL;
        if (param != null) {
            String body = param.toString();
            resp = httpRequest.post(baseURL, input, length, output)
        }
        return resp;
    }

    /**
     * 调用WCF Web Service，POST JSON格式参数，将Response转换为String
     * 
     * @param method
     * @param param
     * @return
     */
    public String postJSONAndGetString(String method, JSONObject param) {
        byte[] bytes = postJSON(method, param);
        String s = new String(bytes);
        return s;
    }

    /**
     * 调用WCF Web Service，POST JSON格式参数，将Response转换为JSON对象
     * 
     * @param method
     * @param param
     * @return
     */
    public JSONObject postJSONAndGetJSON(String method, JSONObject param) {
        String s = postJSONAndGetString(method, param);
        try {
            return new JSONObject(s);
        }
        catch(JSONException e) {
            throw new HttpException(1, e, "Failed to convert response to JSONObject: Resp = " + s);
        }
    }

}
